//
//  ModelsViewController.m
//  NinevehglTest
//
//  Created by 郝建林 on 2016/11/12.
//  Copyright © 2016年 CoolTools. All rights reserved.
//

#import "ModelsViewController.h"

@interface ModelsViewController ()
{
    NSArray *models;
}
@end

@implementation ModelsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"models" ofType:@"json"];
    @try {
        if(filePath == nil)
            @throw [NSException exceptionWithName:@"FileNotFound" reason:@"models.json file not found" userInfo:nil];
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        NSError *error = nil;
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
        if(error)
            @throw [NSException exceptionWithName:@"JSON Error" reason:@"Cannot parse JSON" userInfo:@{@"error": error}];
        if(![json isKindOfClass:[NSArray class]])
            @throw [NSException exceptionWithName:@"JSON Error" reason:@"JSON object is not NSArray" userInfo:nil];
        else
            models = (NSArray*)json;
    }
    @catch (NSException *exception) {
        NSLog(@"load models failed: %@", exception);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return models.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"model" forIndexPath:indexPath];
    NSDictionary *model = models[indexPath.row];
    cell.textLabel.text = model[@"name"];
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *model = models[indexPath.row];
    [self.delegate onModelSelected:model];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
